package com.jw.qme.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jw.qme.domain.dto.MessageDTO;
import com.jw.qme.domain.po.Message;
import com.jw.qme.domain.vo.MessageVO;
import com.jw.qme.mapper.MessageMapper;
import com.jw.qme.service.MessageService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: com.jw.qme.service.impl
 * Datetime: 2025/4/4 下午7:31
 * Description:
 *
 * @author 汪佳泉
 * @version 1.0
 * @since 1.0
 */
@Service
@RequiredArgsConstructor
public class MessageServiceImpl extends ServiceImpl<MessageMapper, Message>
        implements MessageService {

    private final MessageMapper messageMapper;

    // 每页查询数量
    private Integer size = 20;

    @Override
    public List<MessageVO> getMessageByUsername(MessageDTO messageDTO) {
        if(messageDTO.getUsername() == null) throw new RuntimeException("对方账户为空");
        String fromName = (String)StpUtil.getLoginId();
        String toName = messageDTO.getUsername();
        LocalDateTime lastTime = messageDTO.getLastTimestamp();
        List<Message> messages = messageMapper.getMessages(fromName, toName, lastTime, size);
        // 先将数据反转
        if(messages != null && messages.size() > 0){
            Collections.reverse(messages);
        }
        return BeanUtil.copyToList(messages, MessageVO.class);
//        return messages.stream()
//                .map(message -> new MessageVO(
//                        message.getSenderId(),
//                        message.getReceiverId(),
//                        message.getContent(),
//                        message.getTimestamp(),
//                        message.getIsRead())).collect(Collectors.toList());
    }

}
